﻿<%@ Control Language="C#" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<%@ Import Namespace="ArbolandiaBL" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
    public delegate void ReloadGridFromUsr();
    public event ReloadGridFromUsr reloadgrid;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!ArbolandiaBL.Security.ValidLogin())
        {
            X.AddScript("this.parent.LogOut();");
        }
        if (!X.IsAjaxRequest)
        {
            dpfImageSizeSubCat.Text = ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_TITLE;
            dpfImageSizeSubCatSmall.Text = ConstantsBL.SIZE_IMAGE_PRODUCT_SMALL_TITLE;
            this.CategoryStore.DataSource = new Service().GetCategorys();
            this.CategoryStore.DataBind();
            storeProduct.DataSource = new Service().GetAllProductsAdmin();
            storeProduct.DataBind();
        }
    }

    public Store GridStore { get; set; }

    public void Show()
    {
        this.SubcategoryDetailsWindow.Show();
    }

    public void SetSubCategory(Product_SubCategory subCategory)
    {
        pnlImageSubcategory.Reset();
        CompanyInfoTab.SetValues(subCategory);
        ReloadGrid(subCategory.Id);
        ReloadGridImage(subCategory.Id);
    }
    protected void ReloadGrid(Int32 subcategoryId)
    {
        storeGridProducts.DataSource = new Service().GetProductsSimpleListBySubCategory(subcategoryId);
        storeGridProducts.DataBind();
    }
    protected void ReloadGridImage(Int32 subcategoryId)
    {

        storeImagesSubcategory.DataSource = new Service().GetPictureSubcategory(subcategoryId);
        storeImagesSubcategory.DataBind();
    }
    protected void SaveSubcategory(object sender, DirectEventArgs e)
    {
        //NorthwindDataContext db = new NorthwindDataContext();
        int id;
        int.TryParse(e.ExtraParams["id"], out id);

        Product_SubCategory subc = new Product_SubCategory();
        subc.Id = id;
        subc.Name = this.NameSubcategory.Text;
        subc.MetaKeywords = this.MetaKeywords.Text;
        subc.FullDescription = this.FullDescription.Text;
        subc.VideoUrl = this.txtVideoUrl.Text;

        int catid = 0;
        if (this.Product_CategoryId.SelectedItem != null)
        {
            Int32.TryParse(this.Product_CategoryId.SelectedItem.Value, out catid);
        }
        subc.Product_CategoryId = catid;

        if (subc.Product_CategoryId == 0)
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.WARNING,
                Title = "Advertencia",
                Message = "Debe Elegir la categoria Asociada para guardar el registro."
            });
        }
        else
        {
            new Service().InsertUpdateSubCategory(subc);
            this.SubcategoryDetailsWindow.Hide();
            if (id == 0)
            {
                ReloadGridParent();
            }
            else
            {
                var record = this.GridStore.GetById(id);
                CompanyInfoTab.UpdateRecord(record);
                record.Commit();
            }
        }
    }

    protected void ReloadGridParent()
    {
        reloadgrid();
    }
    protected void btnDelete_Click(object sender, DirectEventArgs e)
    {
        Int32 subcategoryId, productid = 0;

        Int32.TryParse(e.ExtraParams["id"], out subcategoryId);

        foreach (SelectedRow row in this.RowSelectionModel1.SelectedRows)
        {
            Int32.TryParse(row.RecordID, out productid);
        }
        if (subcategoryId > 0 && productid > 0)
        {
            new Service().DeleteSubCategoryGroup(productid, subcategoryId);
            ReloadGrid(subcategoryId);
        }
        else
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.WARNING,
                Title = "Alerta",
                Message = "Favor de Seleccionar un registro"
            });
            return;
        }

    }

    protected void btnAddProduct_Click(object sender, DirectEventArgs e)
    {
        var addObj = new Product_SubCategoryGroup();
        Int32 subcategoryId, productid;
        if (cmbProductId.SelectedItem != null) { Int32.TryParse(cmbProductId.SelectedItem.Value, out productid); }
        else { productid = 0; }
        Int32.TryParse(e.ExtraParams["id"], out subcategoryId);
        if (subcategoryId > 0)
        {
            if (productid > 0)
            {
                addObj.Product_SubCategoryId = subcategoryId;
                addObj.Product_ProductId = productid;
                new Service().InsertSubCategoryGroup(addObj);
                ReloadGrid(subcategoryId);
            }
            else
            {

                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.WARNING,
                    Title = "Alerta",
                    Message = "Favor de Seleccionar un producto valido"
                });
                return;
            }
        }
        else
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.WARNING,
                Title = "Alerta",
                Message = "Favor de Guardar Primero Datos principales de la Subcategoria"
            });
            return;
        }

    }
    protected void UploadClick(object sender, DirectEventArgs e)
    {
        string tpl = "Uploaded file: {0}<br/>Size: {1} bytes";
        if (this.uploadField.HasFile && this.uploadFieldSmall.HasFile &&
            (this.uploadField.PostedFile.FileName.ToLower().Contains(".jpg")))
        {
            Int32 subcategoryId; Int32.TryParse(e.ExtraParams["id"], out subcategoryId);
            if (subcategoryId > 0)
            {

                Guid pictureGuid = Guid.NewGuid();
                Guid pictureGuidSmall = Guid.NewGuid();

                string extension = Path.GetExtension(this.uploadField.PostedFile.FileName);
                string extensionSmall = Path.GetExtension(this.uploadFieldSmall.PostedFile.FileName);

                string pathfile = System.Configuration.ConfigurationManager.AppSettings["imagesfolder"];
                string pathFileSmall = pathfile;

                string filename = pictureGuid + extension;
                string filenameSmall = pictureGuidSmall + extension;

                pathfile = Server.MapPath(@"~" + @"\" + pathfile + @"\" + filename);
                pathFileSmall = Server.MapPath(@"~" + @"\" + pathFileSmall + @"\" + filenameSmall);


                new Service().SaveRezizeImage(pathfile, uploadField.PostedFile.InputStream, ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_HEIGHT, ConstantsBL.SIZE_IMAGE_PRODUCT_CATEGORY_WIDTH);
                new Service().SaveRezizeImage(pathFileSmall, uploadFieldSmall.PostedFile.InputStream, ConstantsBL.SIZE_IMAGE_PRODUCT_SMALL_HEIGHT, ConstantsBL.SIZE_IMAGE_PRODUCT_SMALL_WIDTH);

                //Save Guid
                Picture pic = new Picture()
                {
                    IsFullSize = true,
                    Url = "http://hostimages/" + System.Configuration.ConfigurationManager.AppSettings["imagesfolder"] + "/" + filename,
                    ToolTip = "",
                    MimeType = "",
                    LinkUrl = "",
                    IsEnabled = true,
                    GuidId = pictureGuid,
                    GroupdId = 0
                };
                Picture picSmall = new Picture()
                {
                    IsFullSize = false,
                    Url = "http://hostimages/" + System.Configuration.ConfigurationManager.AppSettings["imagesfolder"] + "/" + filenameSmall,
                    ToolTip = "",
                    MimeType = "",
                    LinkUrl = "",
                    IsEnabled = true,
                    GuidId = pictureGuidSmall,
                    GroupdId = 0
                };
                new Service().InsertPictureSubcategory(subcategoryId, pictureGuid, pic, pictureGuidSmall, picSmall);

                ReloadGridImage(subcategoryId);
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "Exito",
                    Message = string.Format(tpl, this.uploadField.PostedFile.FileName, this.uploadField.PostedFile.ContentLength)
                });
            }
            else
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.WARNING,
                    Title = "Alerta",
                    Message = "Favor de Guardar Primero Datos principales de la Subcategoria"
                });
                return;
            }

        }
        else
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.ERROR,
                Title = "Error",
                Message = "No se pudo cargar el archivo. Favor de Seleccionar los 2 archivos validos necesarios. ( JPG )."
            });
        }
    }
    protected void btnDeleteImageSubcategory_Click(object sender, DirectEventArgs e)
    {
        Int32 subcategoryId; Int32.TryParse(e.ExtraParams["id"], out subcategoryId);
        if (subcategoryId > 0)
        {

            new Service().DeletePictureSubcategory(subcategoryId);
            ReloadGridImage(subcategoryId);
            Ext.Net.Notification.Show(new Ext.Net.NotificationConfig
            {
                Title = Constants.TITLE_DELETE,
                Icon = Ext.Net.Icon.PageSave,
                AutoHide = true,
                Html = Constants.NOTIFY_DELETED
            });
        }
        else
        {
            X.Msg.Show(new MessageBoxConfig
            {
                Buttons = MessageBox.Button.OK,
                Icon = MessageBox.Icon.WARNING,
                Title = "Alerta",
                Message = "Favor de Guardar Primero Datos principales de la Subcategoria"
            });
            return;
        }
    }

</script>
<script type="text/javascript">
    var selectionChanged = function (selModel, selected) {
        var count = selected.length, s = count != 1 ? "s" : "";
        App.gridProducts.setTitle("Simple GridPanel (" + count + " item" + s + " selected)");
    };
</script>
<ext:Window ID="SubcategoryDetailsWindow" runat="server" Icon="Group" Title="Subcategoria Detalle"
    Width="700" Height="450" AutoShow="false" Modal="true" Hidden="true" Layout="Fit">
    <Items>
        <ext:TabPanel ID="TabPanel1" runat="server" ActiveTabIndex="0" Border="false" DeferredRender="false">
            <Items>
                <ext:FormPanel ID="CompanyInfoTab" runat="server" Title="Informacion" Icon="ChartOrganisation"
                    DefaultAnchor="100%" BodyPadding="5">
                    <Items>
                        <ext:TextField ID="IdSubcategory" runat="server" FieldLabel="ID" Disabled="true"
                            Name="Id" />
                        <ext:TextField ID="NameSubcategory" runat="server" FieldLabel="Nombre" Name="Name" />
                        <ext:ComboBox ID="Product_CategoryId" runat="server" FieldLabel="Categoria" Name="Product_CategoryId"
                            AllowBlank="true" DisplayField="Name" ValueField="Id" TypeAhead="true" QueryMode="Local"
                            ForceSelection="true" TriggerAction="All" EmptyText="Seleccionar categoria..."
                            Width="250">
                            <Store>
                                <ext:Store runat="server" ID="CategoryStore">
                                    <Model>
                                        <ext:Model ID="Model1" runat="server" IDProperty="Id">
                                            <Fields>
                                                <ext:ModelField Name="Id" />
                                                <ext:ModelField Name="Name" />
                                            </Fields>
                                        </ext:Model>
                                    </Model>
                                </ext:Store>
                            </Store>
                        </ext:ComboBox>
                        <ext:TextArea ID="FullDescription" Height="120" FieldLabel="Descripcion General"
                            LabelAlign="Top" runat="server" Name="FullDescription">
                        </ext:TextArea>
                        <ext:TextField ID="txtVideoUrl" FieldLabel="Youtube VideoId" LabelAlign="Top" runat="server"
                            Name="VideoUrl">
                        </ext:TextField>
                        <ext:HtmlEditor runat="server" Height="160" ID="MetaKeywords" LabelAlign="Top" Name="MetaKeywords"
                            AutoScroll="true" Visible="false" Hidden="true" />
                    </Items>
                </ext:FormPanel>
                <ext:FormPanel ID="pnlImageSubcategory" runat="server" Title="Imagen Subcategoria"
                    Icon="LayoutContent" DefaultAnchor="100%" BodyPadding="5">
                    <TopBar>
                        <ext:Toolbar ID="toolbSubcategoryImages" runat="server">
                            <Items>
                                <ext:Button ID="btnUploadImage" runat="server" Text="Subir Fotos" Icon="Images">
                                    <DirectEvents>
                                        <Click OnEvent="UploadClick" Before="if (!#{pnlImageSubcategory}.getForm().isValid()) { return false; } 
                                                            Ext.Msg.wait('Cargando Imagenes...', 'Cargando');"
                                            Failure="Ext.Msg.show({ 
                                                            title   : 'Error', 
                                                            msg     : 'Error durante la carga', 
                                                            minWidth: 200, 
                                                            modal   : true, 
                                                            icon    : Ext.Msg.ERROR, 
                                                            buttons : Ext.Msg.OK 
                                                        });">
                                            <ExtraParams>
                                                <ext:Parameter Name="id" Value="#{IdSubcategory}.getValue()" Mode="Raw" />
                                            </ExtraParams>
                                        </Click>
                                    </DirectEvents>
                                </ext:Button>
                            </Items>
                        </ext:Toolbar>
                    </TopBar>
                    <Items>
                        <ext:FieldSet ID="FieldSet1" runat="server">
                            <Items>
                                <ext:FieldContainer ID="fieldcontainer2" runat="server" Layout="HBoxLayout">
                                    <Items>
                                        <ext:FileUploadField ID="uploadField" runat="server" Width="400" Icon="Attach" AllowBlank="false">
                                        </ext:FileUploadField>
                                        <ext:ToolbarSeparator ID="ToolbarSeparator1" runat="server">
                                        </ext:ToolbarSeparator>
                                        <ext:DisplayField ID="dpfImageSizeSubCat" runat="server" LabelAlign="Right" />
                                    </Items>
                                </ext:FieldContainer>
                                <ext:FieldContainer ID="fieldcontainer4" runat="server" Layout="HBoxLayout">
                                    <Items>
                                        <ext:FileUploadField ID="uploadFieldSmall" runat="server" Width="400" Icon="Attach"
                                            AllowBlank="false">
                                        </ext:FileUploadField>
                                        <ext:ToolbarSeparator ID="ToolbarSeparator2" runat="server">
                                        </ext:ToolbarSeparator>
                                        <ext:DisplayField ID="dpfImageSizeSubCatSmall" runat="server" LabelAlign="Right" />
                                    </Items>
                                </ext:FieldContainer>
                                <ext:FieldContainer ID="fieldcontainer3" runat="server">
                                    <Items>
                                        <ext:GridPanel ID="gridImageSubcategory" runat="server" ClientIDMode="Static" AutoScroll="true"
                                            Height="300">
                                            <Store>
                                                <ext:Store ID="storeImagesSubcategory" runat="server">
                                                    <Model>
                                                        <ext:Model ID="Model5" runat="server" IDProperty="GuidId">
                                                            <Fields>
                                                                <ext:ModelField Name="GuidId" />
                                                                <ext:ModelField Name="Name" />
                                                                <ext:ModelField Name="url" />
                                                            </Fields>
                                                        </ext:Model>
                                                    </Model>
                                                </ext:Store>
                                            </Store>
                                            <ColumnModel>
                                                <Columns>
                                                    <ext:TemplateColumn ID="TemplateColumn2" runat="server" Text="Archivo" Flex="15"
                                                        DataIndex="url" TemplateString='<img style="width:60px;height:45px;" src="{url}" />' />
                                                    <ext:Column ID="Column2" runat="server" Text="Nombre" Flex="35" DataIndex="Name" />
                                                </Columns>
                                            </ColumnModel>
                                            <View>
                                                <ext:GridView ID="GridView2" runat="server" EmptyText="No Images to Display" />
                                            </View>
                                            <SelectionModel>
                                                <ext:RowSelectionModel ID="RowSelectionModel2" runat="server" Mode="Single" />
                                            </SelectionModel>
                                            <Listeners>
                                                <SelectionChange Fn="selectionChanged" />
                                            </Listeners>
                                            <Buttons>
                                                <ext:Button ID="btnDeleteImageSubcategory" runat="server" Text="Eliminar">
                                                    <DirectEvents>
                                                        <Click OnEvent="btnDeleteImageSubcategory_Click">
                                                            <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{SubcategoryDetailsWindow}.body}" />
                                                            <ExtraParams>
                                                                <ext:Parameter Name="id" Value="#{IdSubcategory}.getValue()" Mode="Raw" />
                                                            </ExtraParams>
                                                        </Click>
                                                    </DirectEvents>
                                                </ext:Button>
                                            </Buttons>
                                        </ext:GridPanel>
                                    </Items>
                                </ext:FieldContainer>
                            </Items>
                        </ext:FieldSet>
                    </Items>
                </ext:FormPanel>
                <ext:FormPanel ID="ProductsTab" runat="server" Title="Productos Subcategoria" Icon="LayoutContent"
                    DefaultAnchor="100%" BodyPadding="5">
                    <Items>
                        <ext:FieldSet ID="fsetProductMain" runat="server">
                            <Items>
                                <ext:FieldContainer ID="fieldcontainerAddProduct" runat="server" Layout="HBoxLayout">
                                    <Items>
                                        <ext:ComboBox ID="cmbProductId" runat="server" FieldLabel="Categoria" Name="Id" AllowBlank="true"
                                            DisplayField="Name" ValueField="Id" TypeAhead="true" QueryMode="Local" ForceSelection="true"
                                            TriggerAction="All" EmptyText="Seleccionar producto..." Width="350">
                                            <Store>
                                                <ext:Store runat="server" ID="storeProduct">
                                                    <Model>
                                                        <ext:Model ID="Model2" runat="server" IDProperty="Id">
                                                            <Fields>
                                                                <ext:ModelField Name="Id" />
                                                                <ext:ModelField Name="Name" />
                                                                <ext:ModelField Name="url" />
                                                            </Fields>
                                                        </ext:Model>
                                                    </Model>
                                                </ext:Store>
                                            </Store>
                                        </ext:ComboBox>
                                        <ext:ToolbarSeparator ID="tblSeparate" runat="server">
                                        </ext:ToolbarSeparator>
                                        <ext:Button ID="btnAddProduct" runat="server" Text="Agregar">
                                            <DirectEvents>
                                                <Click OnEvent="btnAddProduct_Click">
                                                    <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{SubcategoryDetailsWindow}.body}" />
                                                    <ExtraParams>
                                                        <ext:Parameter Name="id" Value="#{IdSubcategory}.getValue()" Mode="Raw" />
                                                    </ExtraParams>
                                                </Click>
                                            </DirectEvents>
                                        </ext:Button>
                                    </Items>
                                </ext:FieldContainer>
                                <ext:FieldContainer ID="fieldcontainer1" runat="server">
                                    <Items>
                                        <ext:GridPanel ID="gridProducts" runat="server" ClientIDMode="Static" AutoScroll="true"
                                            Height="300">
                                            <Store>
                                                <ext:Store ID="storeGridProducts" runat="server">
                                                    <Model>
                                                        <ext:Model ID="Model3" runat="server" IDProperty="Id">
                                                            <Fields>
                                                                <ext:ModelField Name="Id" />
                                                                <ext:ModelField Name="Name" />
                                                                <ext:ModelField Name="url" />
                                                            </Fields>
                                                        </ext:Model>
                                                    </Model>
                                                </ext:Store>
                                            </Store>
                                            <ColumnModel>
                                                <Columns>
                                                    <ext:TemplateColumn ID="TemplateColumn1" runat="server" Text="Archivo" Flex="15"
                                                        DataIndex="url" TemplateString='<img style="width:60px;height:45px;" src="{url}" />' />
                                                    <ext:Column ID="Column1" runat="server" Text="Nombre" Flex="35" DataIndex="Name" />
                                                </Columns>
                                            </ColumnModel>
                                            <View>
                                                <ext:GridView ID="GridView1" runat="server" EmptyText="No Images to Display" />
                                            </View>
                                            <SelectionModel>
                                                <ext:RowSelectionModel ID="RowSelectionModel1" runat="server" Mode="Single" />
                                            </SelectionModel>
                                            <Listeners>
                                                <SelectionChange Fn="selectionChanged" />
                                            </Listeners>
                                            <Buttons>
                                                <ext:Button ID="btnDelete" runat="server" Text="Eliminar">
                                                    <DirectEvents>
                                                        <Click OnEvent="btnDelete_Click">
                                                            <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{SubcategoryDetailsWindow}.body}" />
                                                            <ExtraParams>
                                                                <ext:Parameter Name="id" Value="#{IdSubcategory}.getValue()" Mode="Raw" />
                                                            </ExtraParams>
                                                        </Click>
                                                    </DirectEvents>
                                                </ext:Button>
                                            </Buttons>
                                        </ext:GridPanel>
                                    </Items>
                                </ext:FieldContainer>
                            </Items>
                        </ext:FieldSet>
                    </Items>
                </ext:FormPanel>
            </Items>
        </ext:TabPanel>
    </Items>
    <Buttons>
        <ext:Button ID="SaveButton" runat="server" Text="Save" Icon="Disk">
            <DirectEvents>
                <Click OnEvent="SaveSubcategory" Failure="Ext.MessageBox.alert('Saving failed', 'Error during ajax event');">
                    <EventMask ShowMask="true" Target="CustomTarget" CustomTarget="={#{SubcategoryDetailsWindow}.body}" />
                    <ExtraParams>
                        <ext:Parameter Name="id" Value="#{IdSubcategory}.getValue()" Mode="Raw" />
                    </ExtraParams>
                </Click>
            </DirectEvents>
        </ext:Button>
        <ext:Button ID="CancelButton" runat="server" Text="Cancel" Icon="Cancel">
            <Listeners>
                <Click Handler="this.up('window').hide();" />
            </Listeners>
        </ext:Button>
    </Buttons>
</ext:Window>
